<template>
    <el-card>
        <div slot="header">
            <span>账号添加</span>
        </div>
        <el-form ref="ruleForm" :rules="rules" :model="ruleForm" label-width="100px">
            <el-form-item label="账号" prop="account">
                <el-input v-model="ruleForm.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="管理员" prop="userGroup">
                <el-select v-model="ruleForm.userGroup" placeholder="管理员">
                    <el-option label="普通管理员" value="普通管理员"></el-option>
                    <el-option label="超级管理员" value="超级管理员"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">添加</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>


<script>

import { userRepeat, userAdd } from '@/api/user.js'
export default {
    data () {
        let checkUser = async function (rule, value, callback) {
            let res = await userRepeat({ account: value })
            if (res.data.code === 201) {
                callback(new Error(res.data.msg))
            } else if (value.length >= 3) {
            } else {
                callback(new Error('账号名长度在3个字符以上'))
            }
        }
        return {
            ruleForm: {
                account: '',
                password: '',
                userGroup: ""
            },
            rules: {
                account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { validator: checkUser, trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                ],
                userGroup: [{ required: true, message: '请选择管理员', trigger: 'change' }]
            }
        }
    },
    methods: {

        onSubmit () {
            this.$refs.ruleForm.validate(async result => {
                if (result) {
                    let res = await userAdd(this.ruleForm)
                    if (res.data.code === 0) {
                        this.$router.push('/account/list')
                    }
                } else {
                    console.log('添加失败');
                }

            })
        },
        reset () {
            this.$refs.ruleForm.resetFields();
        }
    }
}
</script>

<style lang="less" scoped>
.el-from {
    width: 400px;
}

:deep(.el-input) {
    width: 200px
}
</style>